package src.Sixteen;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class Weather extends Thread{

    String weather = "节目预报：八点有大型晚会，请收听";
    int port = 9898;
    InetAddress inetAddress = null;
    MulticastSocket socket = null;

    public Weather(){
        try {
            inetAddress = InetAddress.getByName("224.225.10.0");
            socket = new MulticastSocket(port);
            socket.setTimeToLive(1);
            socket.joinGroup(inetAddress);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void run(){
        while (true){
            DatagramPacket packet = null;
            byte data[] = weather.getBytes();
            packet = new DatagramPacket(data,data.length,inetAddress,port);
            System.out.println(new String(data));
            try {
                socket.send(packet);
                sleep(3000);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Weather w = new Weather();
        w.start();
    }
}
